﻿using System;
using System.Collections.Generic;
using System.Linq;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Saisie_des_prélèvements.Models;
using Saisie_des_prélèvements.ViewModels;
using Saisie_des_prélèvements.Common;
using Windows.UI.Popups;
using System.Collections.ObjectModel;


// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace Saisie_des_prélèvements.Views
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class TakenNewPage : Saisie_des_prélèvements.Common.LayoutAwarePage
    {
        int CurrentClientTaken = 0;
        string TakenCode = string.Empty;
        public TakenNewPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            CurrentClientTaken = int.Parse(navigationParameter.ToString());
            using (var db = new SQLite.SQLiteConnection(App.DBPath))
            {
                k_client_taken info = db.Table<k_client_taken>().Where(c => c.client_taken_id == CurrentClientTaken).First();

                txtClientCode.Text = info.client_taken_code;
                txtNoDos.Text = info.client_seq;
            }

            //_NPRODUITS = (new NPRODUITViewModel()).GetProductSelection();
            //spt.DataContext = new CollectionViewSource { Source = _NPRODUITS };
            cboProduct.ItemsSource = (new NPRODUITViewModel()).GetProductSelection();
            cboControl.ItemsSource = (new PLANCONTViewModel()).GetPlanControlSelection();
            cboSecteur.ItemsSource = (new SECTEURSViewModel()).GetSecteurSelection();
            cboProduct_SelectionChanged(null, null);
            cboControl_SelectionChanged(null, null);
            cboSecteur_SelectionChanged(null, null);
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            RadioButton r = (RadioButton)sender;
            if (r.Tag == null) return;
            switch (int.Parse(r.Tag.ToString()))
            {
                case 1 :
                    lblControl.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    cboControl.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    txtControl.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    lblSecteur.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    cboSecteur.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    txtSecteur.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    cboControl_SelectionChanged(null, null);
                    break;
                case 2 :
                    lblControl.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    cboControl.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    txtControl.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    lblSecteur.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    cboSecteur.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    txtSecteur.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    cboSecteur_SelectionChanged(null, null);
                    break;
                default :
                    lblControl.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    cboControl.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    txtControl.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    lblSecteur.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    cboSecteur.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    txtSecteur.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    cboProduct_SelectionChanged(null, null);
                    break;
            }
        }

        private void txtProduct_GotFocus(object sender, RoutedEventArgs e)
        {
            ComboBox[] cbos = new ComboBox[] { cboProduct, cboControl, cboSecteur };
            TextBox T = (TextBox)sender;
            cbos[int.Parse(T.Tag.ToString())].IsDropDownOpen = true;
        }

        private void cboProduct_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (rdoProduct.IsChecked == false) return;
            if (cboProduct.SelectedValue == null) cboProduct.SelectedValue = cboProduct.Items[0];
            TakenCode = ((NPRODUITViewModel)cboProduct.SelectedValue).PRD_CODE;
            itemListView.ItemsSource = (new ANALYSESViewModel()).GetAnalyzeProductSelection(TakenCode);
        }

        private void cboControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (rdoControl.IsChecked == false) return;
            if (cboControl.SelectedValue == null) cboControl.SelectedValue = cboControl.Items[0];
            TakenCode = ((PLANCONTViewModel)cboControl.SelectedValue).PC_CODE;
            itemListView.ItemsSource = (new ANALYSESViewModel()).GetAnalyzePlanSelection(TakenCode);
        }

        private void cboSecteur_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (rdoSecteur.IsChecked == false) return;
            if (cboSecteur.SelectedValue == null) cboSecteur.SelectedValue = cboSecteur.Items[0];
            TakenCode = ((SECTEURSViewModel)cboSecteur.SelectedValue).SE_CODE;
            itemListView.ItemsSource = (new ANALYSESViewModel()).GetAnalyzeSecteurSelection(TakenCode);
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            byte TakenType = (byte)((bool)rdoProduct.IsChecked ? 0 : (bool)rdoControl.IsChecked ? 1 : 2);

            
            var db = new SQLite.SQLiteConnection(App.DBPath);

            var newTaken = new k_taken()
            {
                prod_code = ((NPRODUITViewModel)cboProduct.SelectedValue).PRD_CODE,
                taken_type = TakenType,
                taken_code = TakenCode,
                client_taken_id = CurrentClientTaken,
                surv_code = null,
                taken_point_code = null,
                taken_point_label = null,
                taken_point_modifiable = 0,
                taken_date = null,
                days_taken = null,
                months_taken = null,
                years_taken = null,
                taken_comment = null,
                taken_point_day = 0,
                taken_date_next = null,
                taken_date_last = null,
                amount = 0,
                user_create = App.CurrentUserId,
                date_create = DateTime.Now,
            };

            db.Insert(newTaken);

            int TakenID = (new TakenViewModel()).GetTakenInfoLast().TakenId;
            itemListView.UpdateLayout();
            List<k_taken_analyze> newAnalyses = new List<k_taken_analyze>();
            foreach (ANALYSESViewModel analyes in (ObservableCollection<ANALYSESViewModel>)itemListView.ItemsSource)
            {
                var newAnalyse = new k_taken_analyze()
                {
                    analyze_code = analyes.Code,
                    analyze_label = analyes.Label,
                    to_do = analyes.TODO,
                    taken_id = TakenID,
                    user_create = App.CurrentUserId,
                    date_create = DateTime.Now
                };

                newAnalyses.Add(newAnalyse);
                
            }
            db.InsertAll(newAnalyses);
            this.Frame.Navigate(typeof(ClientTakenPage), CurrentClientTaken);
        }

        private async void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            // Create the message dialog and set its content; it will get a default "Close" button since there aren't any other buttons being added
            var messageDialog = new MessageDialog(new msg().client_cancel);

            // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers
            messageDialog.Commands.Add(new UICommand("OK", new UICommandInvokedHandler(this.CommandInvokedHandler)));
            messageDialog.Commands.Add(new UICommand(new msg().msgCancel, new UICommandInvokedHandler(this.CommandInvokedHandler)));

            // Set the command that will be invoked by default
            messageDialog.DefaultCommandIndex = 0;

            // Set the command to be invoked when escape is pressed
            messageDialog.CancelCommandIndex = 1;

            // Show the message dialog and wait
            await messageDialog.ShowAsync();
        }

        /// <summary>
        /// Callback function for the invocation of the dialog commands.
        /// </summary>
        /// <param name="command">The command that was invoked.</param>
        private void CommandInvokedHandler(IUICommand command)
        {
            if (command.Label == "OK")
            {
                this.Frame.Navigate(typeof(ClientTakenPage), CurrentClientTaken);
            }
            
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            CheckBox c = (CheckBox)sender;

            ((ObservableCollection<ANALYSESViewModel>)itemListView.ItemsSource).Where(a => a.Code == c.Tag.ToString()).First().TODO = (bool)c.IsChecked;
        }

        private void GoBack(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(ClientTakenPage), CurrentClientTaken);
        }
    }
}
